﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Inaction
{
    public class QueryTableDataLookUpCommand : SqlCommand
    {
        string tableName = string.Empty;

        public DataTable DataTable { get;private set; }
        public QueryTableDataLookUpCommand(string tableName)
        {
            this.tableName = tableName;
        }
        protected override void DoExecute(System.Data.IDbConnection connection)
        {
            var sql = "Select {0} From " + DbProvider.Instance.FormatName(tableName);
            var tableInfo = DbProvider.Instance.GetTable(tableName);
            sql = string.Format(sql, tableInfo.Columns.Select(p => p.IsPrimaryKey
                || p.Name.StartsWith("Code", StringComparison.OrdinalIgnoreCase)
                || p.Name.EndsWith("Name",StringComparison.OrdinalIgnoreCase)));

            using (var cmd = connection.CreateCommand())
            {
                cmd.CommandText = sql;
                DataTable = new DataTable();
                var reader = cmd.ExecuteReader();
                for(int i=0;i< reader.FieldCount;i++)
                {
                    var columnName = reader.GetName(i);
                    var c = tableInfo.Columns.FirstOrDefault(p => p.Name.Equals(columnName, StringComparison.OrdinalIgnoreCase));
                    DataTable.Columns.Add(c.DisplayName);
                }
                while(reader.Read())
                {
                    var row = DataTable.NewRow();
                    for(int i=0;i< reader.FieldCount;i++)
                    {
                        row[i]= reader.GetValue(i);
                    }
                    DataTable.Rows.Add(row);
                }
            }
        }
    }
}
